<?php

require_once dirname(__FILE__).'/../lib/tesisGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/tesisGeneratorHelper.class.php';

/**
 * tesis actions.
 *
 * @package     sistema_estadisticas
 * @subpackage  tesis
 * @author      Your name here
 * @version     SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class tesisActions extends autoTesisActions
{

	public function executeShow(sfWebRequest $request)
	{
		$table = TesisTable::getInstance();
		$this->tesis = $table->fetchOne($request->getParameter('id'));
		$this->forward404Unless($this->tesis, 'El proyecto de tesis no existe');
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->wizard = new TesisWizard();
		$this->wizard->clean();
		$this->form = $this->wizard->getForm();
	}
	
	public function executeCreate(sfWebRequest $request)
	{
		$this->wizard = new TesisWizard();
		$this->processFormWizard($request, $this->wizard);
		$this->form = $this->wizard->getForm();
		$this->setTemplate('new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->tesis = TesisTable::getInstance()->fetchOne($request->getParameter('id'));
		$this->form = new TesisForm($this->tesis);
		$this->form->embedPertinenciaForm();
	}

	public function executeUpdate(sfWebRequest $request)
	{
		//$this->tesis = $this->getRoute()->getObject();
		$this->tesis = TesisTable::getInstance()->fetchOne($request->getParameter('id'));
		$this->form = $this->configuration->getForm($this->tesis);
		$this->form->embedPertinenciaForm();

		$this->processForm($request, $this->form);
		//$this->tesis = $this->form->getObject();

		$this->setTemplate('edit');
	}

	protected function processFormWizard(sfWebRequest $request, TesisWizard $wizard)
	{
		$this->wizard->setStep($request->getParameter('paso'));
		$wizard->bind($request);
		$form = $wizard->getForm();
		$tesis = null;

		if ($request->hasParameter('_previous'))
		{
			$wizard->previousStep();
			return;
		}

		if ($form->isValid())
		{
			if ($wizard->isLastStep())
			{
				try
				{ 
					$tesis = $wizard->save();
				}
				catch (Exception $ex)
				{
					$this->getUser()->setFlash('error', 'La tesis no se pudo guardar porque se ha producido un error');
					return sfView::SUCCESS;
				}
				
				$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $tesis)));
				$notice = 'El proyecto se ha creado correctamente.';
				
				if ($request->hasParameter('_save_and_add'))
				{
					$this->getUser()->setFlash('notice', $notice.' Ahora puede crear otro.');

					$this->redirect('@tesis_new');
				}
				else
				{
					$this->getUser()->setFlash('notice', $notice);
					$this->redirect('@tesis_show?id=' . $tesis->id);
				}
			}
			else
			{
				$wizard->nextStep();
			}
		}
		else
		{
			$this->getUser()->setFlash('error', 'No se puede continuar porque se ha producido algún error.', false);
		}
	}

}
